import {
  getToken,
  setToken,
  delToken,
  getUserKind,
  delUserKind,
  setUserKind,
} from "@/utils/storage";
import { login } from "@/http/api/user";
// 存储用户令牌和角色信息
const state = {
  token: getToken(),
  roles: [], //角色
  userKind: getUserKind(),
};

const mutations = {
  SET_TOKEN: (state, token) => {
    setToken(token);
    state.token = token;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_USER_KIND: (state, userKind) => {
    setUserKind(userKind);
    state.userKind = userKind;
  },
};

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo)
        .then((res) => {
          commit("SET_TOKEN", res.data.token);
          // commit("SET_USER_KIND", res.data.userKind);
          commit("SET_USER_KIND", "1");
          resolve(res.data);
        })
        .catch((err) => {
          console.log(err, "err");
        });
    });
  },
  // 获取用户角色信息
  getInfo({ commit, state }) {
    return new Promise((resolve) => {
      const roles = state.userKind === "1" ? ["admin"] : ["jerry"];
      commit("SET_ROLES", roles);
      resolve({ roles });
    });
  },
  // 重置令牌
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      commit("SET_ROLES", []);
      delToken();
      delUserKind();
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
